﻿using System;
using System.Collections.Generic;
using System.Linq;
using Model.Entities;
using Model.Repositories;

namespace Presenter.Users
{
    public class SignUpPresenter
    {
        private ISignUpView _view;

        public SignUpPresenter(ISignUpView view)
        {
            _view = view;
            _view.EntityCreated += ViewEntityCreated;

            _view.GetAllInterests(GetAllInterests());
        }

        public void Reload(ISignUpView view)
        {
            _view = view;
            _view.EntityCreated += ViewEntityCreated;

            _view.GetAllInterests(GetAllInterests());
        }

        void ViewEntityCreated(string email, string password, string nickname, string fullname, string job, DateTime birthday, Dictionary<string, string> interests)
        {
            var obj = new User
                          {
                              Email = email,
                              Password = password,
                              NickName = nickname,
                              FullName = fullname,
                              Job = job,
                              BirthDay = birthday
                          };
            
            if (interests != null)
                foreach (var key in interests.Keys)
                {
                    var parent = RepositoryManager.Instance.InterestRepository.GetByTitle(interests[key]);
                    if (parent != null)
                        obj.Interests.Add(new Interest
                                              {
                                                  Title = key,
                                                  Parent = parent
                                              });
                    else
                        obj.Interests.Add(new Interest
                                              {
                                                  Title = key
                                              });
                }

            var res = RepositoryManager.Instance.UserRepository.Insert(obj);
            _view.CanSignIn = res != null;

            if (res != null)
                _view.SetSessionParameters(obj.Id, obj.Email, obj.Password);
        }

        private Dictionary<int, string> GetAllInterests()
        {
            var interests = RepositoryManager.Instance.InterestRepository.GetAll();
            return interests != null ? interests.ToDictionary(o => o.Id, o => o.Title) : null;
        }
    }
}

